package com.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.food.entity.dto.FoodDto;
import com.food.entity.pojo.Food;
import com.food.entity.vo.PageVo;
import com.food.mapper.FoodMapper;
import com.food.service.FoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-03
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {

    @Autowired
    private FoodMapper foodMapper;

    @Override
    public PageVo<Food> listFood(FoodDto foodDto) {
        Page<Food> page = new Page<>(foodDto.getPage(), foodDto.getSize());
        LambdaQueryWrapper<Food> queryWrapper = new LambdaQueryWrapper<>();
        if(foodDto.getName() != null){
            queryWrapper.like(Food::getName, foodDto.getName());
        }
        if(foodDto.getCategory() != null){
            queryWrapper.like(Food::getCategory, foodDto.getCategory());
        }
        Page<Food> paged = page(page, queryWrapper);
        // 获取总记录数
        long total = page.getTotal();
        // 将总记录数转换为整型
        Integer count = Integer.valueOf((int) total);
        List<Food> records = paged.getRecords();
        return new PageVo<>(count, records);
    }

    @Override
    public void updateFood(Food food) {
        int i = foodMapper.updateById(food);
        if(i < 0){
            //todo: 修改失败
        }
    }

    @Override
    public void addFood(Food food) {
        LambdaQueryWrapper<Food> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Food::getName, food.getName());
        Food food1 = foodMapper.selectOne(queryWrapper);
        if(food1 != null){
            //todo: 添加失败，已有同名美食
        }
        foodMapper.insert(food);
    }

    @Override
    public void deleteFood(Integer id) {
        int i = foodMapper.deleteById(id);
        if(i < 0){
            //todo: 删除失败
        }
    }
}
